<template>
  <div class="types">
    <div class="previous">
      <el-button type="primary" class="add_btn" @click="addRootType"
        >添加分类</el-button
      >
    </div>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      ref="tableDom"
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="id" width="180" label="编号" sortable>
      </el-table-column>
      <el-table-column label="等级">
        <template slot-scope="scope">
          <span>{{ typeData[scope.row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="分类名称"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="opt_btn"
            @click="handleAdd(scope.$index, scope.row)"
            v-if="scope.row.type != '3'"
            >添加</el-button
          >
          <el-button
            size="mini"
            class="opt_btn"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            class="opt_btn"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="currentChange"
      :current-page="page"
      :page-size="size"
      layout="total, prev, pager, next"
      :total="total"
      background
    ></el-pagination>

    <el-dialog :title="title" :visible.sync="addDialog" width="30%">
      <el-form
        label-width="120px"
        :model="typeForm"
        :rules="typerules"
        ref="typeForm"
      >
        <el-form-item label="等级：">
          <span>{{ typeForm.levelname }}</span>
        </el-form-item>
        <el-form-item label="分类名称：" prop="typename">
          <el-input v-model="typeForm.typename"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('typeForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/api/shopstore";
export default {
  name: "typeList",
  data() {
    return {
      typeData: {
        "1": "一级",
        "2": "二级",
        "3": "三级"
      },
      tableData: [],
      title: "添加分类",
      addDialog: false,

      typeForm: {
        levelname: "",
        typename: ""
      },
      typerules: {
        typename: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      page: 1,
      size: 10,
      total: 0,
      pid: 0,
      loadNodeMap: new Map(),
      selectCurrRow: {},
      type: "1" //1.新增；2修改
    };
  },
  created() {
    this.getListData();
  },
  methods: {
    getListData() {
      let data = {
        keywords: this.keywords,
        page: this.page,
        size: this.size
      };
      api.getTypeList(data).then(res => {
        const { list, count } = res.data;
        list.forEach(item => {
          item.hasChildren = true;
        });
        this.tableData = list;
        this.total = count;
      });
    },
    addRootType() {
      this.addShow();
      this.typeForm.levelname = "一级";
      this.pid = 0;
    },
    addShow() {
      this.addDialog = true;
      this.typeForm.typename = "";
      this.title = "添加分类";
      this.type = "1";
    },
    handleAdd(index, row) {
      this.addShow();
      this.resetForm("typeForm");
      this.typeForm.levelname = this.typeData[row.type + 1];
      this.pid = row.id;
    },
    handleEdit(index, row) {
      this.selectCurrRow = row;
      this.addDialog = true;
      this.resetForm("typeForm");
      this.$nextTick(() => {
        this.typeForm.levelname = this.typeData[row.type];
        this.typeForm.typename = row.name;
      });
      this.title = "编辑分类";
      this.type = "2";
    },
    submitEdit() {
      api
        .editType({ id: this.selectCurrRow.id, name: this.typeForm.typename })
        .then(res => {
          if (res.code == 200200) {
            this.$message.success(res.msg);
            this.addDialog = false;
            this.selectCurrRow.name = this.typeForm.typename;
          } else {
            this.$message.error(err.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    handleDelete(index, row) {
      this.selectCurrRow = row;
      this.$confirm("确定要删除此分类吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.submitDelete();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitDelete() {
      api
        .deleteType({ id: this.selectCurrRow.id })
        .then(res => {
          if (res.code == 200200) {
            this.$message.success(res.msg);
            this.addDialog = false;
            this._reRenderChildrenNodeAfterDel();
          } else {
            this.$message.error(err.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    _reRenderChildrenNodeAfterDel() {
      const { pid } = this.selectCurrRow;
      if (this.loadNodeMap.has(pid)) {
        const { tree, treeNode, resolve } = this.loadNodeMap.get(pid);
        this.$set(this.$refs.tableDom.store.states.lazyTreeNodeMap, pid, []);
        this.load(tree, treeNode, resolve);
      } else {
        // 如果loadNodeMap 中无数据 ，则查询当前tabelData是否存在该条数据
        let index = this.tableData.findIndex(item => {
          return item.id === this.selectCurrRow.id;
        });
        if (index > -1) {
          this.tableData.splice(index, 1);
          this.total--;
        }
        // 判断当前table 条数是否为0；如果为零重置currentPage=1、total=0
        if (this.tableData <= 0) {
          this.page = 1;
          this.total = 0;
        }
      }
    },
    submitForm(typeForm) {
      this.$refs[typeForm].validate(valid => {
        if (valid) {
          if (this.type == "1") {
            this.createShopType();
          } else {
            this.submitEdit();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    createShopType() {
      let params = {
        pid: this.pid,
        name: this.typeForm.typename
      };
      api
        .createType(params)
        .then(res => {
          if (res.code == 200200) {
            this.$message.success(res.msg);
            this.addDialog = false;

            if (this.loadNodeMap.has(this.pid)) {
              const { tree, resolve } = this.loadNodeMap.get(this.pid);
              this.$set(
                this.$refs.tableDom.store.states.lazyTreeNodeMap,
                this.pid,
                []
              );
              api
                .typeChildById({ id: this.pid })
                .then(res => {
                  let list = res.data;
                  list.forEach(item => {
                    item.hasChildren = true;
                  });

                  if (res.code == 200200) {
                    resolve(list);
                    tree.hasChildren = true;
                  }
                })
                .catch(err => {
                  console.log(err);
                });
            } else {
              this.selectCurrRow.hasChildren = true;
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
          this.$message.error(err.msg);
        });
    },

    resetForm(typeForm) {
      this.$nextTick(() => {
        this.$refs[typeForm].resetFields();
      });
    },
    currentChange(val) {
      this.page = val;
      this.getListData();
    },
    load(tree, treeNode, resolve) {
      const id = tree.id;
      // 将当前操作报存起来
      this.loadNodeMap.set(id, { tree, treeNode, resolve });
      api
        .typeChildList({ id: tree.id })
        .then(res => {
          let list = res.data;
          if (res.code == 200200) {
            list.forEach(item => {
              item.hasChildren = true;
            });
            resolve(list);
            // 如果数据为空 设置hasChildren为false
            if (list.length <= 0) tree.hasChildren = false;
          } else {
            this.$message({
              message: res.msg,
              type: "warning"
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.types {
  padding: 40px;
  .previous {
    text-align: right;
    padding-bottom: 20px;
  }
}
</style>
